package com.uflower.product.service.impl;

import com.uflower.product.service.CategoryBrandRelationService;
import com.uflower.product.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uflower.common.utils.PageUtils;
import com.uflower.common.utils.Query;

import com.uflower.product.dao.CategoryDao;
import com.uflower.product.entity.CategoryEntity;
import com.uflower.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1 查询所有分类
        List<CategoryEntity> allCategory =    baseMapper.selectList(null);
        // 2 将所有的分类数据封装成树形结构
        //2.1 找到所有的parent_id =0 的分类
        List<CategoryEntity> firstLevelCategory = allCategory.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid()==0)//在所有的分类数据中过滤处一级分类
                .peek((categoryEntity)->categoryEntity.setChildCategory(getChildCategoryList(categoryEntity,allCategory)))//通过递归插座的一级分类的子分类
                .sorted((category1,category2)->category1.getSort() == null?0:category1.getSort()-(category2.getSort() == null?0:category2.getSort()))
                .collect(Collectors.toList());//最终将得到的数据收集为一个集合
        return firstLevelCategory;
    }

    @Override
    public void removeCategoryByIds(List<Long> catIds) {
        //TODO 检查当前分类是否被别的地方引用
        categoryDao.deleteBatchIds(catIds);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        // 递归查找父级分类 225 25 2
        List<Long> parentPath =  findParentPath(catelogId,paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities  =   baseMapper
                .selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid",0));
        return categoryEntities;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        List<CategoryEntity> leve1Categorys= getLevel1Categorys();
        Map<String,List<Catelog2Vo>> catelog2VoListMap=   leve1Categorys.stream().collect(Collectors.toMap(k->k.getCatId().toString(), v->{
            List<CategoryEntity> level2Categroys =  baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid",v.getCatId()));
            List<Catelog2Vo> catelog2Vos = null;
            if(level2Categroys != null){
                catelog2Vos = level2Categroys.stream().map(l2->{
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(),null,l2.getCatId().toString(),l2.getName());
                    List<CategoryEntity> level3Categorys = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid",l2.getCatId()));
                    if(level3Categorys !=null){
                        List<Catelog2Vo.Catelog3Vo>catelog3VoList = level3Categorys.stream().map(l3->{
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(),l3.getCatId().toString(),l3.getName());
                            return  catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatelog3VoList(catelog3VoList);
                    }
                    return  catelog2Vo;
                }).collect(Collectors.toList());
            }
            return  catelog2Vos;
        }));
        return catelog2VoListMap;
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths) {
        // 1 收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId =  this.getById(catelogId);
        if(byId.getParentCid() != 0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    // 递归查找 在所有的分类数据中查找 root一级分类下的所有的子分类
    private List<CategoryEntity> getChildCategoryList(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> childCategoryList =   all.stream()
                .filter(categoryEntity->categoryEntity.getParentCid().equals(root.getCatId()))
                //找到子分类
                .peek(categoryEntity->categoryEntity.setChildCategory(getChildCategoryList(categoryEntity,all)))
                // 分类排序
                .sorted((category1,category2)->category1.getSort() == null?0:category1.getSort()-(category2.getSort() == null?0:category2.getSort()))
                .collect(Collectors.toList());
        return  childCategoryList;
    }
}